package com.gitee.fanx.retty.demo.controller;

import com.gitee.fanx.retty.demo.common.ServiceException;
import com.gitee.fanx.retty.demo.vo.User;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author fanhang
 */
@RestController
@RequestMapping("/user")
public class NoteController implements InitializingBean {
	private List<User> userList = new ArrayList<>();
	private AtomicInteger id = new AtomicInteger(0);

	@GetMapping("/list")
	public List<User> userList() {
		return userList;
	}

	@GetMapping("/getById")
	public User user(@RequestParam("id") Integer id, @RequestHeader("token") String token) {
		System.out.println(token);
		if (token.length() > 10) {
			throw new ServiceException(454, "fdsfsd");
		}
		Assert.state(Objects.equals("8527", token), "token错误");
		return userList.stream().filter(i -> Objects.equals(i.getId(), id)).findFirst().get();
	}

	@GetMapping("/search")
	public List<User> search(@RequestParam String name) {
		return userList.stream().filter(i -> i.getName().contains(name)).collect(Collectors.toList());
	}

	@PostMapping("/add")
	public User post(@RequestBody User user) {
		user.setId(id.incrementAndGet());
		this.userList.add(user);
		return user;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		userList.add(new User(id.incrementAndGet(), "张三", 12));
		userList.add(new User(id.incrementAndGet(), "李四", 15));
		userList.add(new User(id.incrementAndGet(), "王麻子", 56));
		userList.add(new User(id.incrementAndGet(), "小六", 25));
		userList.add(new User(id.incrementAndGet(), "老白", 29));
		userList.add(new User(id.incrementAndGet(), "白眉", 78));
	}
}
